package cn.project.dao;

import cn.project.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Component("userTemDao")
public class UserTemDaoImple implements UserTempDao {

    @Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;


    /**
     * JdbcTemplate的query方法
     一个字符串，SQL语句
     一个RowMapper对象，从ResultSet里提取数值并构造一个实体对象返回，在这里就是员工对象。

     * @return
     */
    public static final RowMapper rowMapper=new ParameterizedRowMapper() {

        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            User  user=new User();
            user.setUserid(resultSet.getInt("userid"));
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            return user;
        }
    };

    public List<User> getAllUser() {
        String sql="select * from user";
        List<User>list=jdbcTemplate.query(sql,rowMapper);
        return list;
    }
    /*
    * 多条件模糊查询
    * */
    public List <User> getAllUser(User user) {
        StringBuilder sb=new StringBuilder("select * from user where 1=1 ");
        List plist=new ArrayList();
        if(user!=null){
            if(user.getUsername() != null && user.getUsername().trim().length()>0){
                sb.append(" and username like ?");
                plist.add("%"+user.getUsername()+"%");
            }
            if(user.getPassword() != null && user.getPassword().trim().length()>0){
                sb.append(" and password like ?");
                plist.add("%"+user.getPassword()+"%");
            }
        }
        Object[] params=plist.toArray();
        List<User>list =jdbcTemplate.query(sb.toString(),params,rowMapper);
        return list;
    }

    public User findById(int userid) {

        String sql="select * from user where userid=?";
        List<User>list=jdbcTemplate.query(sql,rowMapper,userid );
        return  list.size()>0 ? list.get(0) :null;
    }

    public int save(User user) {
    String sql="insert into user(username,password) values(?,?)";
    Object[] params={user.getUsername(),user.getPassword()};
        jdbcTemplate.update(sql,params);
        return 0;
    }

    public int update(User user) {

        return 0;
    }

    public int delete(int userid) {

        return userid;
    }
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
